import React, { Component } from 'react';
import { Collapse, Form, Col, Row, Input, Select, DatePicker, Modal, Icon, Button } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import styles from '@/pages/Operate.less';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import AntdUpload from '@/components/AntdUpload';
import prompt from '@/components/Prompt';
import RepairInfo from './RepairInfo';
import UploadFile from './UploadFile';
import SearchSelect from '@/components/SearchSelect';
import { columns1 } from '@/pages/Common/common';
import AdButton from '@/components/AdButton';
import AntdInput from '@/components/AntdInput';
import router from 'umi/router';
import { codes } from './utils';
const dateFormat = 'YYYY-MM-DD';
const Panel = Collapse.Panel;
const { TextArea } = Input;
const { Option } = Select;

@connect(({ repair, loading, common }) => ({
  repair,
  loading: loading.effects['repair/repairDetail'],
  dictObject: common.dictObject,
}))
@Form.create()
export default class RepairOperate extends Component {
  constructor(props) {
    super(props);
    this.state = {
      activeKey: ['1', '2'],
      fileList: [],
      deleteFileIds: [],
      ownCompany: '',
      visible: false,
      visibleFile: false,
      cars: [],
    };
    this.paneSize = ['1', '2'];
  }

  componentDidMount() {
    const {
      repair: { detail },
      match: { params },
      dispatch,
    } = this.props;

    if (params.id) {
      const id = params.id;
      dispatch({
        type: 'repair/repairDetail',
        payload: { id },
        callback: data => {
          data && this.setFileList(data.attachments);
          this.setState({ cars: [{ id: data.vehicleId }] });
        },
      });
      dispatch({
        type: 'repair/repairInfoList',
        payload: { id },
      });
    }
    // 查询字典：
    //币种：
    this.props.dispatch({
      type: 'common/querytDictByCode',
      payload: { code: 'currency-type' },
    });
    // 查询字典：保养类型
    this.props.dispatch({
      type: 'common/querytDictByCode',
      payload: { code: 'upkeep-type' },
    });
  }
  // 设置图片
  setFileList = list => {
    this.setState({ fileList: list });
  };

  // 切换收缩框
  callback = key => {
    this.setState({
      activeKey: key,
    });
  };

  // 明细查看详情
  showDetail = () => {
    this.setState({ visible: true });
  };

  // 明细关闭详情
  repairInfoHandleCancel = () => {
    this.setState({ visible: false });
  };

  // 明细翻页
  handleStandardTableChange = params => {
    this.dispatchFun('repair/repairList', params);
  };

  // 点击新增明细
  addrepairInfo = e => {
    e.stopPropagation();
    const {
      id,
      match: { params },
    } = this.props;
    if (params.id || (id !== 0 && id !== -1)) {
      this.setState({ visible: true });
    } else {
      prompt({ type: 'warn', title: '温馨提示', content: '请先添加维修,再添加明细' });
    }
  };
  importFile = e => {
    e.stopPropagation();
    const {
      id,
      match: { params },
    } = this.props;
    const detailId = params.id || (id !== 0 && id !== -1);
    if (detailId) {
      this.setState({ visibleFile: true });
    } else {
      prompt({ content: '请先添加维修', type: 'warn' });
    }
  };
  // dispatch 方法
  dispatchFun(type, params) {
    const { dispatch } = this.props;
    dispatch({
      type: type,
      payload: params,
    });
  }

  // 添加 或 编辑操作
  operatePaneButton = e => {
    e.stopPropagation();
    e.preventDefault();

    const { ownCompany, cars } = this.state;

    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { repairTime, mdsCompanyId, ...value } = values;
        const { fileList, deleteFileIds } = this.state;
        if (repairTime) {
          value.repairTime = moment(repairTime).format(dateFormat);
        }
        value.fileTokens = fileList.filter(file => file.response).map(file => file.response.data);
        //保存车辆
        if (cars.length > 0) {
          const vehicleId = cars.map(v => {
            return v.id;
          });
          value.vehicleId = vehicleId.join(',');
        } else {
          value.vehicleId = '';
        }
        const {
          match: { params },
          dispatch,
        } = this.props;
        if (params.id) {
          if (deleteFileIds.length > 0) {
            value.deleteFileIds = deleteFileIds;
          }
          value.id = params.id;
          dispatch({
            type: 'repair/repairOperate',
            payload: value,
            callback: () => {
              this.dispatchFun('repair/repairList', {});
            },
          });
        } else {
          dispatch({
            type: 'repair/repairOperate',
            payload: value,
            callback: res => {
              if (!res) return;
              data.attachments && this.setFileList(data.attachments);
              this.setState({ cars: [{ id: data.vehicleId }] });
              dispatch({
                type: 'repair/repairDetail',
                payload: { id: res },
                callback: data => {
                  //新增变编辑页面：
                  dispatch({
                    type: 'common/setTabsName',
                    payload: {
                      id: res,
                      name: data.repairNo,
                      isReplaceTab: true,
                    },
                    callback: result => {
                      if (result) {
                        router.push(`/manageCar/repairList/editrepair/${res}`);
                      }
                    },
                  });
                },
              });
              this.dispatchFun('repair/repairList', {});
            },
          });
        }
      }
    });
  };

  // 上传图片
  handleChange = fileList => {
    this.setState({ fileList });
  };

  // 删除图片
  onRemove = deleteFileIds => {
    this.setState({
      deleteFileIds,
    });
  };
  getValue = values => {
    const ownCompany = values.map(v => {
      return v.ownCompanyName;
    });
    this.setState({
      cars: values,
      ownCompany,
    });
  };

  render() {
    const {
      list,
      type,
      form: { getFieldDecorator },
      repair: { detail, repairInfoList },
      loading,
      dictObject,
      match: { params },
    } = this.props;
    const detailId = params.id;
    const { activeKey, fileList, ownCompany, visible, visibleFile, cars } = this.state;
    const data = repairInfoList[detailId] ? repairInfoList[detailId] : {};

    const panel = detail[detailId];

    const genExtraBasicInfo = () => (
      <div className={styles.headerTitle}>
        <span>{panel ? panel.repairNo : '新增维修'}</span>
        <div>
          <AdButton
            type="primary"
            onClick={e => this.operatePaneButton(e)}
            text="保存"
            code={panel ? codes.edit : codes.add}
          />
        </div>
      </div>
    );
    const repairInfoParams = {
      id: detailId,
      data,
      type: 'list',
      loading,
      showDetail: this.showDetail,
      visible: visible,
      change: this.handleStandardTableChange,
      handleCancel: this.repairInfoHandleCancel,
    };
    const prefixSelector = type =>
      getFieldDecorator(type == 'payAble' ? 'currencyType' : 'currencyType1', {
        initialValue: 'CNY',
      })(
        <Select placeholder="请选择" disabled={type == 'payAble' ? true : false}>
          {dictObject['currency-type'] &&
            dictObject['currency-type'].map(item => <Option key={item.code}>{item.value}</Option>)}
        </Select>
      );
    const _gutter = { md: 8, lg: 24, xl: 48 };
    const _col = { md: 12, sm: 24 };
    const _row = { md: 24 };
    return (
      <div className={styles.CollapseUpdate}>
        <UploadFile
          visibleFile={visibleFile}
          handleCancel={() => {
            this.setState({ visibleFile: false });
          }}
          id={detailId}
        />
        <PageHeaderWrapper title={genExtraBasicInfo()}>
          <Collapse activeKey={activeKey} onChange={key => this.callback(key)} bordered={false}>
            {this.paneSize.map((item, panelId) => {
              return (
                <Panel
                  header={`${panelId === 0 ? '基础信息' : '明细'}`}
                  key={`${panelId + 1}`}
                  className={styles.customPanelStyle}
                  extra={
                    panelId === 0 ? null : (
                      <span>
                        <AdButton
                          type="primary"
                          onClick={e => this.importFile(e)}
                          style={{ marginRight: 8 }}
                          text="导入"
                          code={codes.upload}
                        />
                        <AdButton
                          type="primary"
                          onClick={e => this.addrepairInfo(e)}
                          text="新增"
                          code={codes.addPaper}
                        />
                      </span>
                    )
                  }
                >
                  {panelId === 0 && (
                    <div className={styles.tableListForm}>
                      <Form layout="inline">
                        <Row gutter={_gutter}>
                          <Col {..._col}>
                            <Form.Item label="单据号">
                              {getFieldDecorator('repairNo', {
                                initialValue: panel ? panel.repairNo : '保存后系统自动生成',
                              })(<Input placeholder="请输入单据号" disabled={true} />)}
                            </Form.Item>
                          </Col>
                          <Col {..._col}>
                            <Form.Item label="车牌号">
                              {getFieldDecorator('vehicleId', {
                                rules: [{ required: true, message: '请选择' }],
                                initialValue: panel ? panel.vehicleId : undefined,
                              })(
                                <SearchSelect
                                  dataUrl="tms/tms-repair/selectVehicle"
                                  url="tms/tms-repair/selectVehicleView_s" // selectedData只只有id时需要传url
                                  selectedData={this.state.cars} // 选中值
                                  multiple={false} // 是否多选
                                  showValue="cartPlateOneNo"
                                  searchName="cartPlate"
                                  columns={columns1} // 表格展示列
                                  onChange={this.getValue} // 获取选中值
                                  scrollX={480}
                                  id="repair_2"
                                />
                              )}
                            </Form.Item>
                          </Col>
                        </Row>
                        <Row gutter={_gutter}>
                          <Col {..._col}>
                            <Form.Item label="所属公司">
                              {getFieldDecorator('mdsCompanyId', {
                                initialValue: ownCompany
                                  ? ownCompany
                                  : panel && panel.ownCompanyName,
                              })(<Input placeholder="请输入" disabled={true} />)}
                            </Form.Item>
                          </Col>
                          <Col {..._col}>
                            <Form.Item label="类型">
                              {getFieldDecorator('类型', {
                                initialValue: panel ? panel.vehicleId : undefined,
                              })(
                                <Select>
                                  <Option value="维修">维修</Option>
                                  <Option value="一级保养">一级保养</Option>
                                  <Option value="二级保养">二级保养</Option>
                                  <Option value="三级保养">三级保养</Option>
                                </Select>
                              )}
                            </Form.Item>
                          </Col>
                        </Row>
                        <Row gutter={_gutter}>
                          <Col {..._col}>
                            <Form.Item label="送修时间">
                              {getFieldDecorator('repairTime', {
                                rules: [{ required: true, message: '请选择' }],
                                initialValue:
                                  panel && panel.repairTime
                                    ? moment(panel.repairTime, dateFormat)
                                    : null,
                              })(<DatePicker style={{ width: '100%' }} />)}
                            </Form.Item>
                          </Col>
                          <Col {..._col}>
                            <Form.Item label="送保时间">
                              {getFieldDecorator('upkeepTime', {
                                rules: [{ required: true, message: '' }],
                                initialValue:
                                  panel && panel.upkeepTime
                                    ? moment(panel.upkeepTime, dateFormat)
                                    : null,
                              })(<DatePicker style={{ width: '100%' }} />)}
                            </Form.Item>
                          </Col>
                        </Row>
                        <Row gutter={_gutter}>
                          <Col {..._col}>
                            <Form.Item label="维修厂">
                              {getFieldDecorator('repairFactory', {
                                initialValue: panel ? panel.repairFactory : '',
                              })(<Input placeholder="请输入" />)}
                            </Form.Item>
                          </Col>
                          <Col {..._col}>
                            <Form.Item label="送修人">
                              {getFieldDecorator('repairPerson', {
                                rules: [{ required: true, message: '' }],
                                initialValue: panel ? panel.repairPerson : '',
                              })(<Input placeholder="请输入" />)}
                            </Form.Item>
                          </Col>
                        </Row>

                        <Row gutter={_gutter}>
                          <Col {..._col}>
                            <Form.Item label="保养类型">
                              {getFieldDecorator('upkeepType', {
                                rules: [{ required: true, message: '请选择送保时间' }],
                                initialValue: panel ? panel.upkeepType : undefined,
                              })(
                                <Select placeholder="请选择">
                                  {dictObject['upkeep-type'] &&
                                    dictObject['upkeep-type'].map(item => (
                                      <Option key={item.code}>{item.value}</Option>
                                    ))}
                                </Select>
                              )}
                            </Form.Item>
                          </Col>
                          <Col {..._col}>
                            <Form.Item label="保养厂">
                              {getFieldDecorator('upkeepFactory', {
                                rules: [{ required: true, message: '' }],
                                initialValue: panel ? panel.upkeepFactory : '',
                              })(<Input placeholder="请输入" />)}
                            </Form.Item>
                          </Col>
                        </Row>
                        <Row gutter={_gutter}>
                          <Col {..._col}>
                            <Form.Item label="送保人">
                              {getFieldDecorator('upkeepPerson', {
                                rules: [{ required: true, message: '' }],
                                initialValue: panel ? panel.upkeepPerson : '',
                              })(<Input placeholder="请输入" />)}
                            </Form.Item>
                          </Col>
                          <Col {..._col}>
                            <Form.Item label="当前里程">
                              {getFieldDecorator('currentMileage', {
                                rules: [{ required: true, message: '' }],
                                initialValue: panel ? panel.currentMileage : '',
                              })(<Input placeholder="请输入" />)}
                            </Form.Item>
                          </Col>
                        </Row>

                        <Row gutter={_gutter}>
                          <Col {..._col}>
                            <Form.Item label="应付金额">
                              {getFieldDecorator('totalFee', {
                                initialValue: panel ? panel.totalFee : '',
                              })(
                                <AntdInput
                                  mode="money"
                                  label="应付金额"
                                  placeholder=""
                                  addonBefore={prefixSelector('payAble')}
                                  disabled={true}
                                />
                              )}
                            </Form.Item>
                          </Col>
                          <Col {..._col}>
                            <Form.Item label="实付金额">
                              {getFieldDecorator('totalFee2', {
                                initialValue: panel ? panel.totalFee2 : '',
                              })(
                                <AntdInput
                                  mode="money"
                                  label="实付金额"
                                  placeholder="长度不超过18位可保留两位小数"
                                  addonBefore={prefixSelector('payActual')}
                                />
                              )}
                            </Form.Item>
                          </Col>
                        </Row>

                        <Row gutter={_gutter}>
                          <Col {..._col}>
                            <Form.Item label="支付方式">
                              {getFieldDecorator('支付方式', {
                                initialValue: panel ? panel.payType : undefined,
                              })(
                                <Select>
                                  <Option value="现金">现金</Option>
                                  <Option value="月结">月结</Option>
                                </Select>
                              )}
                            </Form.Item>
                          </Col>
                        </Row>
                        <Row gutter={_gutter}>
                          <Col {..._row}>
                            <Form.Item label="备注">
                              {getFieldDecorator('remarks', {
                                initialValue: panel ? panel.remarks : '',
                              })(<TextArea placeholder="请输入" rows={4} />)}
                            </Form.Item>
                          </Col>
                        </Row>
                        <Row gutter={_gutter}>
                          <Col {..._row}>
                            <Form.Item label="票据">
                              {getFieldDecorator('fileTokens')(
                                <AntdUpload
                                  fileList={fileList}
                                  onRemove={this.onRemove}
                                  handleChange={this.handleChange}
                                  fileLength="5"
                                />
                              )}
                            </Form.Item>
                          </Col>
                        </Row>
                      </Form>
                    </div>
                  )}
                  {panelId === 1 && <RepairInfo {...repairInfoParams} />}
                </Panel>
              );
            })}
          </Collapse>
        </PageHeaderWrapper>
      </div>
    );
  }
}
